package org.jaaksi.kottlindemo.test

import java.util.concurrent.locks.ReentrantLock

class TestMethod {
  fun main(args: Array<String>) {
    twoAndThree { a, b -> a + b }
    twoAndThree { a, b -> a * b }

    var list = listOf<String>()
    list.joinToString { "11" }

    println("Before sync")
    //调用 synchronized 函数
    synchronized(ReentrantLock()) {
      println("Action")
    }
    println("After sync")
  }

  // 声明函数类型，需要将函数参数类型放在括号中，紧接着是一个箭头和函数的返回类型
  fun twoAndThree(operation: (Int, Int) -> Int) {
    //调用函数类型的参数
    val result = operation(2, 3)
    println("The result is $result")
  }

  fun <T> Collection<T>.joinToString(
    separator: String = ",",
    prefix: String = "",
    postfix: String = "",
    transform: ((T) -> String)?//可空函数类型
  ): String {
    val result = StringBuilder(prefix)
    forEachIndexed { index, element ->
      if (index > 0) result.append(separator)
      //调用 invoke 方法执行函数
      result.append(transform?.invoke(element) ?: element.toString())
    }
    result.append(postfix)
    return result.toString()
  }

  //使用 inline 修饰带有函数类型参数的函数
  inline fun <T> synchronized(/*lock: Lock,*/ action: () -> T): T {
    val lock = ReentrantLock()
    lock.lock()
    try {
      return action()
    } finally {
      lock.unlock()
    }

  }
}